package ssllink

import (
	"crypto/rand"
	"fmt"
	"net"
	"os"
	"slapp3/backend/sslink/utils/waterutil"
	"strings"

	"github.com/pion/dtls/v3/pkg/protocol"
)

func InArray[T comparable](array []T, item T) bool {
	for _, v := range array {
		if v == item {
			return true
		}
	}
	return false
}

func Min(init int, other ...int) int {
	minValue := init
	for _, val := range other {
		if val != 0 && val < minValue {
			minValue = val
		}
	}
	return minValue
}

func FirstUpper(s string) string {
	if s == "" {
		return ""
	}
	return strings.ToUpper(s[:1]) + s[1:]
}

func MakeMasterSecret() ([]byte, error) {
	masterSecret := make([]byte, 48)
	masterSecret[0] = protocol.Version1_2.Major
	masterSecret[1] = protocol.Version1_2.Minor
	_, err := rand.Read(masterSecret[2:])
	return masterSecret, err
}

func ResolvePacket(packet []byte) (string, uint16, string, uint16) {
	src := waterutil.IPv4Source(packet)
	srcPort := waterutil.IPv4SourcePort(packet)
	dst := waterutil.IPv4Destination(packet)
	dstPort := waterutil.IPv4DestinationPort(packet)
	return src.String(), srcPort, dst.String(), dstPort
}

func IpMask2CIDR(ip, mask string) string {
	length, _ := net.IPMask(net.ParseIP(mask).To4()).Size()
	return fmt.Sprintf("%s/%v", ip, length)
}

// IpMaskToCIDR 输入 192.168.1.10/255.255.255.255 返回 192.168.1.10/32
func IpMaskToCIDR(ipMask string) string {
	ips := strings.Split(ipMask, "/")
	length, _ := net.IPMask(net.ParseIP(ips[1]).To4()).Size()
	return fmt.Sprintf("%s/%v", ips[0], length)
}

func CopyFile(dstName, srcName string) (err error) {
	input, err := os.ReadFile(srcName)
	if err != nil {
		return err
	}

	err = os.WriteFile(dstName, input, 0644)
	if err != nil {
		return err
	}
	return nil
}
